<template>
  <div class="login-container">
    <!-- 导航 -->
   <van-nav-bar class="login-container-title" left-arrow title="登录" @click.native="$router.back()"/>
   <!-- 表单 -->
   <van-form @submit="onSubmit" ref="LoginForm">
      <van-field
        v-model="user.mobile"
        placeholder="请输入手机号"
        type="number"
        name="phone"
         :rules="[{ required: true, message: '请输入手机号' }]"
      >
      <i slot="left-icon" class="news news-shouji"></i>
      </van-field>
      <van-field
        v-model="user.code"
        name="code"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请输入验证码' }]"
      >
      <i slot="left-icon" class="news news-yanzhengma"></i>
        <template #button>
          <van-count-down :time="time" v-if="IsShowTime" format="ss s" @finish=" IsShowTime = false" />
          <van-button round size="mini" v-else type="default" native-type="button"  @click="sendCode">发送验证码</van-button>
        </template>
      </van-field>
  <div class="login-btn">
    <van-button block type="info" native-type="submit">登录</van-button>
  </div>
</van-form>
  </div>

  
</template>

<script>
import  { login, SendCode } from '@/api/user.js'
  export default {
    name: 'loginIndex',
    data() {
      return {
        user: {
          mobile: '13030190129',
          code: '246810'
        },
        IsShowTime:false,
        time: 60 * 1000,
      }
    },
    methods: {
      // 提交
      async onSubmit(){
        
        // 加载动画
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true,//禁用背景点击
          duration:0 //持续时间，默认是 2000， 如果为0则持续展示
        });
        
        // 提交表单请求登录
        try {
          const {data} = await login(this.user)
          console.log('登录成功', data.data)
          this.$store.commit("setUser",data.data)
          this.$toast.success('登录成功');
        } catch (err) {
          if (err.response.status === 400) {
            this.$toast.fail('登录失败');
          }
        }
      },
      // 发送验证码
     async sendCode() {
        // 1.再次校验手机号
       try {
         await this.$refs.LoginForm.validate('phone')
       } catch (error) {
         return console.log(error);
       }
        // 2.开启倒计时
        this.IsShowTime = true

        // 3.发送验证码（网络请求）
        try {
          await SendCode(this.user.mobile)
          this.$toast.success('发送成功');
        } catch (error) {
          if(error.response.status === 429){
            this.$toast.fail('发送过于频繁');
          }else {
            this.$toast.fail('发送失败，请检查网络');
          }
        }
      }
    },
  }
</script>

<style lang="less" scoped>
  .login-container {
    .news {
      font-size: 37px;
    }
    .login-btn {
      padding: 33px 55px;
    }
  }
</style>